package com.example.bluploader;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.example.bluploader.utils.Connection;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

public class WebAppInterface {
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    private List<Connection> connectionList = new ArrayList<>();
    private MainActivity app;

    public WebAppInterface(MainActivity app) {
        this.app = app;
        // 蓝牙对象（下面使用Android5.0新增的扫描API，扫描返回的结果更友好，比如BLE广播数据以前是byte[] scanRecord，而新API帮我们解析成ScanRecord类）

    }


    /**
     * 扫描所有的ble蓝牙设备
     */
    @SuppressLint("MissingPermission")
    @JavascriptInterface
    public void scan(boolean status) {
        Log.i("---DSH11111-----","111111");
        Log.i("DSH", "onScanResult: " + "呵呵");
        ScanCallback scanCallback = new ScanCallback() {
            @Override
            @SuppressLint("MissingPermission")
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                BluetoothDevice device = result.getDevice(); // 获取BLE设备信息
                Connection connection = new Connection(device.getName() == null ? "匿名" : device.getName(), device.getAddress());

                // 判断是否存在 存在就不再录入并更新
                Boolean have = false;
                for (Connection item : connectionList) {
                    if (item.getAdds().equals(device.getAddress())) {
                        have = true;
                    }
                }
                if (!have) {
                    connectionList.add(connection);
                }
                Gson gson = new GsonBuilder().create();
                app.webView.evaluateJavascript("onScan" + "(" + gson.toJson(connectionList) + ")", null);
                // app.webView.loadUrl("javascript:onScan("+connectionList+")");

            }
        };
        if (status) {
            bluetoothLeScanner.startScan(scanCallback);
        } else {
            bluetoothLeScanner.stopScan(scanCallback);
        }
    }



    final char[] hexArray = "0123456789ABCDEF".toCharArray();
    private  String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    @SuppressLint("MissingPermission")
    @JavascriptInterface
    public void scan(boolean status, String target) {
        Log.i("---DSH222-----","2222");
        ScanCallback scanOneCallback = new ScanCallback() {
            @Override
            @SuppressLint("MissingPermission")
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                BluetoothDevice device = result.getDevice(); // 获取BLE设备信息
                if (target.equals(device.getAddress())) {
                    // saveData(device);
                    Log.i("---DSH-----", "onScanResult: " + bytesToHex(device.));
                    app.webView.evaluateJavascript("onScanOne" + "('" + device.toString() + "')", null);
                }
            }
        };
        if (status) {
            bluetoothLeScanner.startScan(scanOneCallback);
        } else {
            bluetoothLeScanner.stopScan(scanOneCallback);
        }
    }
}
